package cn.edu.gdu.quizpractice.service;

import cn.edu.gdu.quizpractice.entity.ApiResult;
import cn.edu.gdu.quizpractice.entity.ChoiceQuestion;
import cn.edu.gdu.quizpractice.model.QuestionExcelModel;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel导出服务
 */
@Service
@Slf4j
public class ExcelExportService {

    @Autowired
    private IBankService bankService;

    /**
     * 导出题库题目到Excel
     * @param bankName 题库名称
     * @param response HTTP响应对象
     * @throws IOException IO异常
     */
    public void exportBankQuestionsToExcel(String bankName, HttpServletResponse response) throws IOException {
        log.info("开始导出题库 {} 的题目", bankName);
        
        try {
            // 1. 获取题目数据
            List<ChoiceQuestion> questions = bankService.findQuestionsByBankName(bankName);
            
            if (questions == null || questions.isEmpty()) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":500,\"message\":\"没有找到题目数据\"}");
                return;
            }
            
            // 2. 转换为Excel模型
            List<QuestionExcelModel> excelData = convertToExcelModels(questions, bankName);
            
            // 3. 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(bankName + "题库题目", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            
            // 4. 写入Excel
            try {
                EasyExcel.write(response.getOutputStream(), QuestionExcelModel.class)
                        .sheet("题目数据")
                        .doWrite(excelData);
                log.info("题库 {} 的题目导出成功，共 {} 条记录", bankName, excelData.size());
            } catch (Exception e) {
                log.error("导出Excel失败: {}", e.getMessage(), e);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":500,\"message\":\"导出Excel失败: " + e.getMessage() + "\"}");
            }
        } catch (Exception e) {
            log.error("导出Excel失败: {}", e.getMessage(), e);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":500,\"message\":\"导出Excel失败: " + e.getMessage() + "\"}");
        }
    }
    
    /**
     * 将题目对象转换为Excel模型
     * @param questions 题目列表
     * @param bankName 题库名称
     * @return Excel模型列表
     */
    private List<QuestionExcelModel> convertToExcelModels(List<ChoiceQuestion> questions, String bankName) {
        List<QuestionExcelModel> excelData = new ArrayList<>();
        
        for (ChoiceQuestion question : questions) {
            QuestionExcelModel model = new QuestionExcelModel();
            
            // 设置属性
            model.setCquestionId(question.getCquestionId());
            model.setBankName(bankName);
            model.setCqContent(question.getCqContent());
            model.setOptionA(question.getOptionA());
            model.setOptionB(question.getOptionB());
            model.setOptionC(question.getOptionC());
            model.setOptionD(question.getOptionD());
            model.setCorrectAnswer(question.getCorrectAnswer());
            model.setAnalysis(question.getAnalysis());
            model.setDifficulty(question.getDifficulty());
            
            // 处理分类信息
            if (question.getCategoryName() != null) {
                model.setCategoryName(question.getCategoryName().toString());
            }
            
            excelData.add(model);
        }
        
        return excelData;
    }
    
    /**
     * 获取字符串值
     * @param map Map对象
     * @param key 键
     * @return 字符串值
     */
    private String getStringValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        return value != null ? value.toString() : "";
    }
    
    /**
     * 获取整数值
     * @param map Map对象
     * @param key 键
     * @return 整数值
     */
    private Integer getIntValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        
        if (value instanceof Integer) {
            return (Integer) value;
        } else if (value instanceof Number) {
            return ((Number) value).intValue();
        } else {
            try {
                return Integer.parseInt(value.toString());
            } catch (NumberFormatException e) {
                return null;
            }
        }
    }
} 